<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/admin/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/admin/article">博客管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加文章</el-breadcrumb-item>
      <el-button class="back" type="primary" size="mini" @click="$router.back()">返回</el-button>
    </el-breadcrumb>
    <el-card
      ><el-form ref="articleform" :model="article" :rules="articleRules" label-width="80px">
        <el-form-item label="博客标题" prop="tittle">
          <el-input v-model="article.tittle"></el-input>
        </el-form-item>
        <el-form-item label="博客封面" prop="image_address">
          <el-upload
            class="upload_image"
            action="#"
            :headers="headers"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleChange"
            multiple
            :limit="1"
            accept=".png, .jpg, .JPG, .JPEG, .jpeg, .PNG .GIF, .gif"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件,且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="博客作者" prop="author">
          <el-input v-model="article.author"></el-input>
        </el-form-item>
        <el-form-item label="博客分类" prop="category_id">
          <el-select v-model="article.category_id" placeholder="请选择博客分类">
            <el-option v-for="item in category" :key="item.id" :label="item.alias" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="博客摘要" prop="abstract">
          <el-input type="textarea" v-model="article.abstract"></el-input>
        </el-form-item>
        <el-form-item label="博客内容" prop="content">
          <quillEditor class="editor" ref="articleEditor" v-model="article.content" :options="editorOption" @change="quillEditorchange($event)"></quillEditor
          ><input type="file" hidden accept=".png, .jpg, .JPG, .JPEG, .jpeg, .PNG .GIF, .gif" ref="fileBtn" @change="insertImg"
        /></el-form-item>
        <el-form-item label="添加博客">
          <el-button type="primary" @click="addBlog">提交</el-button>
          <el-button @click="cancelAddBLog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'ArticleAdd',
  components: { quillEditor },
  data() {
    return {
      editorLoaded: false,
      editorOption: {
        // 占位配置
        placeholder: '请在这里输入blog内容',
        modules: {
          imageDrop: true,
          imageResize: true,
          // imageDrop: true,
          // imageResize: {
          //   displaySize: true,
          //   handlers: 'tl t r tr bl b br'
          // },
          // modules: [ 'Resize', 'DisplaySize', 'Toolbar' ],
          toolbar: [
            ['bold', 'strike'], //加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], //引用  代码块
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
            [{ color: [] }, { background: [] }], // 颜色选择
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['image', 'video', 'link'], //链接、图片、视频
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ font: ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }] // 字体
          ]
        }
        // 配置工具栏
      },
      article: {
        tittle: '',
        author: '',
        category_id: '',
        abstract: '',
        content: '',
        image_address: ''
      },
      articleRules: {
        tittle: [{ required: true, message: '博客标题不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '博客作者不能为空', trigger: 'blur' }],
        category_id: [{ required: true, message: '请选择博客分类', trigger: 'change' }],
        abstract: [{ required: true, message: '博客摘要不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '博客内容不能为空', trigger: 'blur' }]
        // image_address: [{ required: true, message: '请上传博客封面', trigger: 'blur' }]
      },
      category: [],
      fileList: [],
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  },
  computed: {},

  created() {
    this.getCategories()
  },

  mounted() {
    if (this.$refs.articleEditor) {
      //myQuillEditor改成自己的
      this.$refs.articleEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    }
  },
  updated() {},
  methods: {
    quillEditorchange(e) {
      this.article.content = e.html
    },
    async getCategories() {
      const { result } = await this.$http.get('/categories/all')

      this.category = result.data
    },
    addBlog() {
      if (this.article.image_address == '') {
        this.$message({
          type: 'error',
          message: '请上传博客封面',
          duration: 1000
        })
      }
      this.$refs['articleform'].validate(valid => {
        if (valid) {
          //验证通过
          this.$http
            .post('/article', {
              tittle: this.article.tittle,
              author: this.article.author,
              category_id: this.article.category_id,
              abstract: this.article.abstract,
              content: this.article.content,
              image_address: this.article.image_address
            })
            .then(res => {})
          this.$message({
            type: 'success',
            message: '添加博客成功',
            duration: 500
          })
          this.$refs['articleform'].resetFields()
          this.$router.push('/admin/article')
          this.fileList = []
        }
      })
    },

    handleChange(file, fileList) {
      this.fileList = fileList
      var param = new FormData()
      this.fileList.forEach((val, index) => {
        param.append('file', val.raw)
      })
      this.$http
        .post('/article/upload', param)
        .then(res => {
          this.article.image_address = res.path
          this.$message({
            type: 'success',
            message: '上传文章封面成功',
            duration: 1000
          })
        })
        .catch(err => {})
    },

    cancelAddBLog() {
      this.$refs['articleform'].resetFields()
    },
    async insertImg(e) {
      const files = Array.prototype.slice.call(e.target.files)
      if (!files) {
        return
      }
      let formdata = new FormData()
      formdata.append('file', files[0])
      //使用了axios请求
      const data = await this.$http.post('/article/upload', formdata)
      let selection = this.$refs.articleEditor.quill.getSelection()
      //这里就是返回的图片地址，如果接口返回的不是可以访问的地址，要自己拼接
      let imgUrl = data.path
      //获取quill的光标，插入图片
      this.$refs.articleEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)
      //插入完成后，光标往后移动一位
      this.$refs.articleEditor.quill.setSelection(selection.index + 1)
    },
    imgHandler() {
      this.$refs.fileBtn.click()
    }
  }
}
</script>

<style scoped>
.back {
  position: relative;
  top: -6px;
}
.editor {
  line-height: normal !important;
  /* height: 250px; */
}
.Editor {
  font-size: 18px;
  height: 200px;
}
</style>
